import pandas as pd
import os

def generate_lung_parameters(output_dir):
    """
    生成肺参数相关的多个表格并保存为CSV。
    output_dir: 输出文件夹路径。
    """
    os.makedirs(output_dir, exist_ok=True)

    # 1. Ventilation-perfusion ratio
    df_vq = pd.DataFrame([
        {"Parameter": "Ventilation-perfusion ratio", "Mean": 1, "CV (%)": 35}
    ])
    df_vq.to_csv(os.path.join(output_dir, "ventilation_perfusion_ratio.csv"), index=False)

    # 2. Volumes
    df_vol = pd.DataFrame([
        {"Compartment": "Airways", "Mean (L)": 0.1, "CV (%)": 30},
        {"Compartment": "Alveoli", "Mean (L)": 5.6, "CV (%)": 10},
        {"Compartment": "Pulmonary capilliary blood", "Mean (L)": 0.089, "CV (%)": 20},
        {"Compartment": "Epithelial lining fluid", "Mean (L)": 0.025, "CV (%)": 20},
    ])
    df_vol.to_csv(os.path.join(output_dir, "lung_volumes.csv"), index=False)

    # 3. Granuloma initial bacteria
    df_gran_bac = pd.DataFrame([
        {"Parameter": "Initial bacteria number", "Mean": 20}
    ])
    df_gran_bac.to_csv(os.path.join(output_dir, "granuloma_initial_bacteria.csv"), index=False)

    # 4. Lung location frequency
    df_loc = pd.DataFrame([
        {"Region": "Right Lung - Low Lobe", "Value": 1},
        {"Region": "Right Lung - Middle Lobe", "Value": 0},
        {"Region": "Right Lung - Top Lobe", "Value": 0},
        {"Region": "Left Lung - Low Lobe", "Value": 0},
        {"Region": "Left Lung - Top Lobe", "Value": 0},
    ])
    df_loc.to_csv(os.path.join(output_dir, "lung_location_frequency.csv"), index=False)

    # 5. Granuloma volume and composition
    df_gran_comp = pd.DataFrame([
        {"Parameter": "Macrophage Diameter (um)", "Mean": 21.2, "CV (%)": None},
        {"Parameter": "fMacrophage (% of Granuloma)", "Mean": 50, "CV (%)": None},
        {"Parameter": "f_ISF (% of Granuloma)", "Mean": 10, "CV (%)": 30},
        {"Parameter": "fOuter Caseum (% of Granuloma)", "Mean": 20, "CV (%)": 30},
        {"Parameter": "fInner Caseum (% of Granuloma)", "Mean": 20, "CV (%)": 30},
    ])
    df_gran_comp.to_csv(os.path.join(output_dir, "granuloma_volume_composition.csv"), index=False)

    # 6. Pretreatment non-replicating bacteria
    df_bac_nr = pd.DataFrame([
        {"Parameter": "Pretreatment number of non-replicating bacteria in caseum (Bₙ)", "Mean": 80, "CV (%)": 30}
    ])
    df_bac_nr.to_csv(os.path.join(output_dir, "pretreatment_nonreplicating_bacteria.csv"), index=False)

    # 7. Surface area
    df_sa = pd.DataFrame([
        {"Region": "Airways", "Mean (m²)": 1.5, "CV (%)": 50},
        {"Region": "Alveoli", "Mean (m²)": 140, "CV (%)": 30},
    ])
    df_sa.to_csv(os.path.join(output_dir, "lung_surface_area.csv"), index=False)

    # 8. Microsomal protein
    df_mp = pd.DataFrame([
        {"Parameter": "Microsomal protein (mg/g)", "Mean": 10.51, "CV (%)": 40}
    ])
    df_mp.to_csv(os.path.join(output_dir, "microsomal_protein.csv"), index=False)

    # 9. pH values by compartment
    df_ph = pd.DataFrame([
        {"Compartment": "Macrophage", "pH": 5},
        {"Compartment": "ISF (Interstitial)", "pH": 6.7},
        {"Compartment": "Caseum", "pH": 7.4},
    ])
    df_ph.to_csv(os.path.join(output_dir, "lung_ph_values.csv"), index=False)

    # 10. Granuloma growth period
    df_growth = pd.DataFrame([
        {"Parameter": "Granuloma Growth Period (days)", "Value": 200}
    ])
    df_growth.to_csv(os.path.join(output_dir, "granuloma_growth_period.csv"), index=False)

    # 11. Enzyme abundance (CYP1A1)
    df_cyp1a1 = pd.DataFrame([
        {"Region": "EM", "Mean (pmol/mg)": 7.36, "CV (%)": 35},
        {"Region": "PM", "Mean (pmol/mg)": 0, "CV (%)": 0},
        {"Region": "IM1", "Mean (pmol/mg)": 0, "CV (%)": 0},
        {"Region": "IM2", "Mean (pmol/mg)": 0, "CV (%)": 0},
        {"Region": "UM", "Mean (pmol/mg)": 0, "CV (%)": 0},
    ])
    df_cyp1a1.to_csv(os.path.join(output_dir, "cyp1a1_abundance.csv"), index=False)

    # 12. Lobe distribution percentages
    df_lobe = pd.DataFrame([
        ["MPPLu distribution",16.66,16.67,16.67,16.67,16.67,8.33,8.33],
        ["Ventilation rate",25.9,12.4,14.8,32.1,14.8,100,100],
        ["Blood flow rate",31.1,11.8,8.6,34.9,8.6,5,2.5],
        ["Alveoli volume",26.3,10.5,15.8,26.3,21.1,50,50],
        ["Absorption area",26.3,10.5,15.8,26.3,21.1,50,50],
        ["Pulmonary capillary volume",16.66,16.67,16.67,16.67,16.67,8.33,8.33],
        ["Pulmonary mass volume",16.66,16.67,16.67,16.67,16.67,8.33,8.33],
        ["Epithelial lining fluid",16.66,16.67,16.67,16.67,16.67,8.33,8.33],
    ], columns=["Parameter","Right Low Lobe","Right Middle Lobe","Right Top Lobe","Left Low Lobe","Left Top Lobe","Lower Airways","Upper Airways"])
    df_lobe.to_csv(os.path.join(output_dir, "lobe_distribution_percentages.csv"), index=False)

    # 13. User defined local pH
    df_local_ph = pd.DataFrame([
        ["Right - Low Lobe",6.7,6.6],
        ["Right - Middle Lobe",6.7,6.6],
        ["Right - Top Lobe",6.7,6.6],
        ["Left - Low Lobe",6.7,6.6],
        ["Left - Top Lobe",6.7,6.6],
        ["Lower Airways",6.7,6.6],
        ["Upper Airways",6.7,6.6],
    ], columns=["Region","Pulmonary Mass pH","Epithelial Lining Fluid pH"])
    df_local_ph.to_csv(os.path.join(output_dir, "user_defined_local_ph.csv"), index=False)

    # 14. Transporters relative abundance
    df_transp = pd.DataFrame([
        ["Basal Uptake 1 (Lung)",1,0],
        ["Basal Uptake 2 (Lung)",1,0],
        ["Basal Efflux 1 (Lung)",1,0],
        ["Basal Efflux 2 (Lung)",1,0],
        ["Apical Uptake 1 (Lung)",1,0],
        ["Apical Uptake 2 (Lung)",1,0],
        ["Apical Efflux 1 (Lung)",1,0],
        ["Apical Efflux 2 (Lung)",1,0],
        ["Uptake (Macrophage)",1,0],
        ["Efflux (Macrophage)",1,0],
    ], columns=["Transporter","Mean","CV (%)"])
    df_transp.to_csv(os.path.join(output_dir, "lung_transporter_relative_abundance.csv"), index=False)

    # 15. Clearance rate data
    df_clear = pd.DataFrame([
        ["UAF(1/h)",0.417,30],
        ["LAF(1/h)",0.083,30],
        ["RTF(1/h)",0.000275,30],
        ["RMF(1/h)",0.000275,30],
        ["RLF(1/h)",0.000275,30],
        ["LTF(1/h)",0.000275,30],
        ["LLF(1/h)",0.000275,30],
    ], columns=["Parameter","Mean","CV (%)"])
    df_clear.to_csv(os.path.join(output_dir, "lung_clearance_rate.csv"), index=False)

    # 16. Activity parameters
    df_activity = pd.DataFrame([
        ["Sitting","Tidal Volume VT(mL)",750,464],
        ["Sitting","Volumetric Flow Rate V(mL/s)",300,217],
        ["Sleeping","Tidal Volume VT(mL)",625,444],
        ["Sleeping","Volumetric Flow Rate V(mL/s)",250,178],
        ["Light Exercise","Tidal Volume VT(mL)",1250,992],
        ["Light Exercise","Volumetric Flow Rate V(mL/s)",833,694],
        ["Heavy Exercise","Tidal Volume VT(mL)",1920,1364],
        ["Heavy Exercise","Volumetric Flow Rate V(mL/s)",1670,1500],
    ], columns=["Activity","Parameter","Male","Female"])
    df_activity.to_csv(os.path.join(output_dir, "lung_activity_parameters.csv"), index=False)

    # 17. Functional Residual Capacity and Dead Space
    df_frc = pd.DataFrame([
        ["Functional Residual Capacity (FRC)(mL)",3301,2681],
        ["Anatomical Dead Space in ET Region (VD(ET)(ml)",50,40],
        ["Anatomical Dead Space in BB Region (VD(BB)(ml)",49,40],
        ["Anatomical Dead Space in bb Region (VD(bb)(ml)",47,44],
    ], columns=["Parameter","Male","Female"])
    df_frc.to_csv(os.path.join(output_dir, "lung_frc_dead_space.csv"), index=False)

    print(f"所有肺参数表格已保存到: {output_dir}")


def generate_lung_parameters_from_df(df):
    """
    批量生成肺参数，输入人口学DataFrame，输出带id的肺参数DataFrame。
    参数均采用原脚本中的均值，不做任何数据内容修改。
    """
    results = []
    for idx, row in df.iterrows():
        person_id = row.get('id', idx)
        # 体积、表面积等均用原脚本均值
        airways_vol = 0.1
        alveoli_vol = 5.6
        cap_blood_vol = 0.089
        epithelial_fluid_vol = 0.025
        airways_sa = 1.5
        alveoli_sa = 140
        vq_ratio = 1
        vq_cv = 35
        results.append({
            'id': person_id,
            'Lung_airways_volume_L': airways_vol,
            'Lung_alveoli_volume_L': alveoli_vol,
            'Lung_capillary_blood_volume_L': cap_blood_vol,
            'Lung_epithelial_fluid_volume_L': epithelial_fluid_vol,
            'Lung_airways_surface_area_m2': airways_sa,
            'Lung_alveoli_surface_area_m2': alveoli_sa,
            'Lung_ventilation_perfusion_ratio': vq_ratio,
            'Lung_ventilation_perfusion_cv_percent': vq_cv
        })
    return pd.DataFrame(results)


def main():
    output_dir = os.path.dirname(os.path.abspath(__file__))
    generate_lung_parameters(output_dir)

if __name__ == "__main__":
    main() 